package net.xumf.web.controller.member.role;

import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import net.xumf.domain.master.SystemRole;
import net.xumf.domain.master.SystemUser;
import net.xumf.service.master.SystemRoleService;
import net.xumf.service.master.SystemUserService;
import net.xumf.support.model.ResponseResult;
import net.xumf.support.model.dto.PageDTO;
import net.xumf.support.model.dto.RolePageDTO;
import net.xumf.support.model.vo.MultiselectControlVO;
import net.xumf.support.model.vo.PageVO;
import net.xumf.web.controller.common.BaseControllerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@Api(value = "角色管理", description = "角色管理")
@RequestMapping("member/roles")
public class SystemRoleController extends BaseControllerImpl<RolePageDTO, SystemRoleService, SystemRole, Integer> {

    @Autowired
    private SystemUserService systemUserService;

    @ApiOperation(value = "获取所有角色")
    @ApiImplicitParam(name = "id", value = "用户id", dataTypeClass = Long.class, paramType = "path")
    @GetMapping("/user/{id}")
    public List<MultiselectControlVO> getAllByUserId(@PathVariable Long id) {
        // 用户拥有的角色
        ArrayList<String> roles = Lists.newArrayList(systemUserService.getById(id).map(SystemUser::getRoles).orElse("").split(","));
        return Lists.newArrayList(service.getAll()).stream().map(role -> MultiselectControlVO.builder()
                .value(role.getRoleId().toString())
                .label(role.getName())
                .title(role.getName())
                .selected(roles.contains(role.getRoleId().toString()))
                .build()).collect(Collectors.toList());
    }

    @Override
    public PageVO getByPage(RolePageDTO pageDTO) {
        return service.getByRoleByNameAndStatus(pageDTO);
    }

}